﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Networking.Proximity;
using Windows.Networking.Sockets;
using Windows.Storage.Streams;
using System.Runtime.InteropServices.WindowsRuntime;
using System.IO;
using Windows.Devices.Bluetooth.Rfcomm;
using Windows.Devices.Bluetooth;
using Windows.Devices.Enumeration;
using System.Globalization;


namespace Bluefly
{


    public class VarioSimulationService : VarioServiceBase, IVarioService
    {


        public VarioSimulationService()
            : base()
        {

        }


        public override void Run()
        {

            setState(ConnectionState.STATE_CONNECTING);

            try
            {
                Connect();
            }
            catch (Exception ex)
            {
                _errors.Add(ex.Message);
                setState(ConnectionState.STATE_ERROR);
            }

        }


        void Connect()
        {

            System.Threading.Tasks.Task.Factory.StartNew(() =>
            {
                try
                {

                    setUpData();

                    System.Threading.Tasks.Task.Delay(400).Wait();

                    _isConnected = true;

                    setState(ConnectionState.STATE_CONNECTED);

                    ListenForData();

                    setState(ConnectionState.STATE_NONE);

                }
                catch (Exception ex)
                {

                    _isConnected = false;

                    lock (_errors)
                    {
                        _errors.Add(ex.Message);
                    }

                    setState(ConnectionState.STATE_ERROR);

                }
                finally
                {
                    _isConnected = false;
                    Disconnect();


                }
            }, TaskCreationOptions.LongRunning);
        }


        protected override void Disconnect()
        {

            
        }


        void ListenForData()
        {

            try
            {

                while (_isConnected)
                {
                    System.Threading.Tasks.Task.Delay(20);

                    OnDeviceSentenceReceived(DummyVarioHardware.Next());
                }

            }
            catch (Exception ex)
            {
                lock (_errors)
                {
                    _errors.Add(ex.Message);
                    setState(ConnectionState.STATE_ERROR);
                }

            }
            finally
            {

            }

        }


        protected override  void OnDeviceSentenceReceived(string line)
        {

            try
            {
                if (string.IsNullOrEmpty(line) || Current == null)
                {
                    return;
                }

                String[] split = line.Split(' ');

                if (string.IsNullOrEmpty(split[0]))
                {
                    return;
                }

                if (split[0] == "PRS")
                {
                    ProcessPressureUpdate(int.Parse(split[1], NumberStyles.HexNumber), split.Length > 2 ? int.Parse(split[2], NumberStyles.HexNumber): default(int?) );
                    RaisePressureChanged(_rawPressure, _dampedAltitude, _rawAltitude, _dampedrate, _kalmanrate);

                }
                else if (split[0] == ("TMP"))
                {
                    this.lastUpdateType = UpdateType.TMP;
                    updateTemperature(int.Parse(split[1]));
                    RaiseTemperatureChanged(int.Parse(split[1]));
                }

                else if (split[0] == "BAT")
                {

                    this.lastUpdateType = UpdateType.BAT;
                    int bat = int.Parse(split[1], NumberStyles.HexNumber);     //bat is in mV
                    RaiseBatteryVoltageChanged((double)chargeFromVolts.getValue(bat / 1000.0));

                }
                else if (split[0] == "BFV")
                {

                    this.lastUpdateType = UpdateType.VER;
                    try
                    {
                        int ver = int.Parse(split[1]);
                        setHardwareVersion(ver);
                    }
                    catch (Exception)
                    {
                        // (NumberFormatException e) {
                        setHardwareVersion(0);
                    }


                }
                else if (split[0] == "BST")
                {
                    this.lastUpdateType = UpdateType.KEYS;
                    //Current.updateHardwareSettingsKeys(line);

                }
                else if (split[0] == "SET")
                {
                    this.lastUpdateType = UpdateType.VALUES;
                    //Current.updateHardwareSettingsValues(line);
                }
            }
            catch (Exception ex)
            { //NumberFormatException e) {
                return;
            }

        }


    }






}
